<?php
/**
 * Description: 登录信息授权，用于已登录状态进行其他账号绑定或删除、更新
 * User: devforma
 * Date: 15/1/5
 * Time: 17:50
 */
require LIB_DIR.'/phpass.class.php';

class AuthHandle implements iController {
    private $weixinDetect = false, $weixinOpenid = '';
    private $registerSource, $registerChannel, $campusChannel, $activity;

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        //校验参数
        if (validateUser($queryArgs) !== 1 || !is_numeric($queryArgs['auth_type'])
            || empty($queryArgs['handle_type']) || empty($queryArgs['auth_id'])) {
            return genOutput(1000);
        }

        //获取注册渠道来源
        $registerInfo = getRegisterInfo($queryArgs);
        $this->registerSource  = $registerInfo['register_source'];
        $this->registerChannel = $registerInfo['register_channel'];
        $this->campusChannel   = $registerInfo['campus_channel'];
        $this->activity        = $registerInfo['register_activity'];

        switch ($queryArgs['auth_type']) {
            case 0: //手机
                $password = empty($queryArgs['password']) ? '' : $queryArgs['password'];
                $output = $this->handlePhone($queryArgs['handle_type'], $queryArgs['user_id'],
                    $queryArgs['auth_id'], $password);
                break;

            case 1: //微博
                $output = $this->handleSocialAccount('weibo', $queryArgs['handle_type'], $queryArgs['user_id'], $queryArgs['auth_id']);
                break;

            case 2: //微信

                if (!empty($queryArgs['app_type']) && $queryArgs['app_type'] === 'dailyplan' &&
                    !empty($queryArgs['app_version']) && version_cmp($queryArgs['app_version'], '1.1') >= 0
                    && !empty($queryArgs['weixin_openid'])) {
                    $this->weixinDetect = true;
                    $this->weixinOpenid = $queryArgs['weixin_openid'];
                }

                $output = $this->handleSocialAccount('weixin', $queryArgs['handle_type'], $queryArgs['user_id'], $queryArgs['auth_id']);
                break;

            case 3: //人人，不再支持
                $output = genOutput(1000);
                break;

            default:
                $output = genOutput(1000);
                break;
        }

        //删除用户信息缓存
        $cacheKey = 'userInfo:'.$queryArgs['user_id'];
        cacheDelete($cacheKey);

        return $output;

    }

    /**
     * 手机号绑定、更新和删除处理
     * 
     * @param string $handleType 行为
     * @param int $userId 用户id
     * @param string $phone 手机号
     * @param string $passwd 绑定手机号时的密码
     * 
     * @return array 返回结果
     */
    private function handlePhone($handleType, $userId, $phone, $passwd) {
        global $uddb;
        
        //手机号是否验证成功
        if (!($value = cacheGet('phone:'.$phone)) || !$value['validated']) {
            return genOutput(1103);
        }
        
        //校验手机号是否存在
        $sql = "SELECT `ID` FROM `{$uddb->userAuthInfo}` WHERE `phone`=:phone";
        $phoneExists = $uddb->getVar($sql, array(':phone' => $phone));
        if ($phoneExists) return genOutput(1102);
        
        $sql = "SELECT * FROM `{$uddb->userAuthInfo}` WHERE `ID`=:ID";
        $user = $uddb->getRow($sql, array(':ID' => $userId));

        switch ($handleType) {
            //无记录或记录非手机号格式，则可以执行add操作
            case 'add':
                if (empty($user)) {
                    //首次绑定手机号需要设定密码
                    if (empty($passwd))  return genOutput(1000);
        
                    $passwd = passDecrypt($passwd, ENCRYPTION_KEY);
                    $phpass = new PasswordHash(8, true);
                    $passwd = $phpass->HashPassword($passwd);
                    $uddb->insert($uddb->userAuthInfo, [
                        'phone'             => $phone,
                        'user_pass'         => $passwd,
                        'register_source'   => $this->registerSource,
                        'register_channel'  => $this->registerChannel,
                        'register_activity' => $this->activity,
                        'campus_channel'    => $this->campusChannel
                    ]);
                    
                    return genOutput(1);
                } elseif (!validatePhone($user->phone)) {
                    //email登录并绑定邮箱
                    $uddb->update($uddb->userAuthInfo, ['phone' => $phone], ['ID' => $user->ID]);
                    return genOutput(1);
                }
                
                return genOutput(1102);
                break;
            
            case 'update':
                //有记录并且是手机号的格式才可以更新手机号的绑定
                if (!empty($user) && validatePhone($phone)) {
                    $uddb->update($uddb->userAuthInfo, ['phone' => $phone], ['ID' => $user->ID]);
                    return genOutput(1);
                }
                
                break;
            
            //解除手机号的绑定，暂时不支持
            /*case 'delete':
                return genOutput(1000);
                break;
            */
        }
        
        return genOutput(1000);
    }
    
    /**
     * 第三方账号的绑定、更新和删除
     *
     * @param string $socialName 第三方平台名称
     * @param string $handleType 行为
     * @param int $userId 系统用户id
     * @param string $socialId 第三方ID
     * 
     * @return array 返回结果
     */
    private function handleSocialAccount($socialName, $handleType, $userId, $socialId) {
        global $uddb;


        if ($socialName == 'weixin' && $this->weixinDetect) {
            $isExists = getUserIdWithWeixin($this->weixinOpenid, $socialId);
        } else {
            $query = "SELECT `ID` FROM `{$uddb->userAuthInfo}` WHERE `$socialName`=:$socialName";
            $isExists = $uddb->getVar($query, array(":$socialName" => $socialId));
        }
        

        if ($isExists) return genOutput(1102);
        
        $query = "SELECT * FROM `{$uddb->userAuthInfo}` WHERE `ID`=:ID";
        $user = $uddb->getRow($query, array(":ID" => $userId));
        if (!empty($user)) {
            $result = $uddb->update($uddb->userAuthInfo, array($socialName => $socialId), array('ID' => $userId));
            
            if ($result) return genOutput(1);
        }
        
        return genOutput(1000);
    }
}